<?php
/**
 * Created by PhpStorm.
 * User: qinlu
 * Date: 2018/7/20
 * Time: 15:22
 */
namespace Admin\Controller;

use Common\Logic\LotteryLogic;

class LotteryController extends BaseController{

    /*
     * 奖品相关
     * */

    /* 奖品列表 */
    public function prizeList(){
        $where = [];
        $keyWord = trim(I('get.key_word',''));
        if($keyWord){
            $where['prize_name']  = array('like', '%'. $keyWord .'%');
            $whereLike['key_word'] = $keyWord;
        }
        $LotteryPrize = M('LotteryPrize');
        $count = $LotteryPrize -> where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数
        foreach($whereLike as $key=>$val) {
            $Page->parameter[$key] = $val;
        }
        $show = $Page->show();// 分页显示输出
        $lotteryData = $LotteryPrize->where($where)->order('prize_id asc')->limit($Page->firstRow.','.$Page->listRows)->select();
        // $Coupon = M('coupon');
        $config = [
            LotteryLogic::COUPON_PRIZE_TYPE => C('POINT_NAME'),
            LotteryLogic::MONEY_PRIZE_TYPE => C('MONEY_NAME'),
            LotteryLogic::GOODS_PRIZE_TYPE => '实物',
        ];

        foreach ($lotteryData as $k => &$value) 
        {
            // if($value['coupon_id'] > 0 )
            // $value['coupon'] = $Coupon->where(['id'=>$value['coupon_id']])->field("id,name,money")->find();
            $value['prize_name_desc'] = $config[$value['category_id']].':'.( $value['category_id'] == LotteryLogic::GOODS_PRIZE_TYPE ? $value['prize_name'] : $value['coupon_id']) ;
            
        }
        $this -> assign('lotteryData',$lotteryData);
        $this->assign('page',$show);// 赋值分页输出
        $this -> display();
    }

    /* 数据验证 */
    public function validate($data){
        $info[] = $data;
        $str = '';
        foreach ($info as $k => $v){
            // if(empty($v['prize_img'])){
            //     $str = '奖品图片不能为空';
            // }
            if(empty($v['prize_name'])){
                $str = '奖品名称不能为空';
            }
            if(!is_numeric($v['prize_weight'])){
                $str = '奖品权重必须为数字';
            }
            // if(!is_numeric($v['prize_sort'])){
            //     $str = '奖品排序必须为数字';
            // }
            // if(!is_numeric($v['prize_num'])){
            //     $str = '奖品排序必须为数字';
            // }
        }
//        exit;
        return $str;
    }

    /* 删除奖品 */
    public function delPrize(){
        if(IS_POST){
            $prize_id = trim(I('post.prize_id',''));
            if(!$prize_id){
                exit(json_encode(['result' => 401,'message' => '无法获取奖品id','data' => []]));
            }
            $LotteryPrize = M('LotteryPrize');
            $result = $LotteryPrize->where('prize_id='.$prize_id)->delete(); //
            if(!$result){
                exit(json_encode(['result' => 402,'message' => '操作失败','data' => []]));
            }else{
                exit(json_encode(['result' => 200,'message' => '操作成功','data' => []]));
            }
        }
    }

    /* 添加奖品 */
    public function addPrize(){
        $LotteryPrize = M('LotteryPrize');
        /* 分类数据 */
        $LotteryCategory = M('LotteryCategory');
        $lotteryCategoryData = $LotteryCategory->select();

        if(IS_POST){
            /* 接值 */
            $prize_id = trim(I('post.prize_id',''));
            $data['prize_name'] = trim(I('post.prize_name','')); //奖品名称
            $data['prize_weight'] = trim(I('post.prize_weight','')); //奖品权重
            $data['prize_num'] = trim(I('post.prize_num','')); //奖品数量
            $data['prize_sort'] = trim(I('post.prize_sort','')); //奖品排序
            $data['check_num'] = trim(I('post.check_num')); //是否校验库存
            $data['category_id'] = trim(I('post.category_id')); //分类id
            $data['coupon_id'] = trim(I('post.coupon_id'));//兑换券金额

            if( $data['category_id'] != LotteryLogic::COUPON_PRIZE_TYPE )
            {
                $data['coupon_id'] = 0;
            }

            if($prize_id){
                $weight = $LotteryPrize->where(["status"=>1,"prize_id"=>["neq",$prize_id]])->sum("prize_weight");
                if($data['prize_weight']+$weight>100)
                {
                    $this -> error('所有奖品的权重值已超出限制');
                }
                $flag = $this -> upload(false); //奖品图片
                if(!empty($flag)){
                    $data['prize_img'] = $flag; //奖品图片
                }
            }else{
                $weight = $LotteryPrize->where(["status"=>1])->sum("prize_weight");
                if($data['prize_weight']+$weight>100)
                {
                    $this -> error('所有奖品的权重值已超出限制');
                }
                $data['prize_img'] = $this -> upload(); //奖品图片
            }
            
            /* 验证 */
            $validateMsg = $this -> validate($data);
            if($validateMsg){
                $this -> error($validateMsg);
                exit;
            }
            /* 添加 */
            if($prize_id){
                $data['prize_id'] = $prize_id;
                $data['update_time'] = time(); //修改时间
                $insert_id = $LotteryPrize -> save($data);
            }else{
                $data['create_time'] = time(); //创建时间
                $insert_id = $LotteryPrize -> add($data);
            }

            if($insert_id){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
            exit;
        }
        if(IS_GET){
            $prize_id = trim(I('get.prize_id',''));
            if($prize_id){
                $weight = $LotteryPrize->where(["prize_status"=>1,"prize_id"=>["neq",$prize_id]])->sum("prize_weight");
                $weight = 100 - $weight;
                $lotteryData = $LotteryPrize->where('prize_id = '.$prize_id)->find();
                if($lotteryData['coupon_id'])
                $lotteryData['coupon'] = M("Coupon")->where(['id'=>$lotteryData['coupon_id']])->field("id,name,money")->find();
            }else{
                $weight = $LotteryPrize->where(["prize_status"=>1])->sum("prize_weight");
                $weight = 100 - $weight;
                if($weight<1)
                {
                    $this->error("奖品权重已达上限，请调整权重");
                }
            }
        }
        $this->assign("coupon_prize_type",LotteryLogic::COUPON_PRIZE_TYPE);
        $this->assign("money_prize_type",LotteryLogic::MONEY_PRIZE_TYPE);
        $this->assign("goods_prize_type",LotteryLogic::GOODS_PRIZE_TYPE);
        $this -> assign('prize_weight', $weight);
        $this -> assign('lotteryData',$lotteryData);
        $this -> assign('lotteryCategoryData',$lotteryCategoryData);
        $this -> display();
    }

    /* 奖品图片上传 */
    public function upload($flag = true){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     UPLOAD_PATH.'lottery/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            if($flag){
                $this->error($upload->getError());
                exit;
            }else{
                return false;
            }
        }else{// 上传成功
            return $info['prize_img']['urlpath'];
        }
    }



    /*
     * 奖品分类
     * */

    /* 分类列表 */
    public function categoryList(){
        $LotteryCategory = M('LotteryCategory');
        $lotteryCategoryData = $LotteryCategory->select();
        $this -> assign('lotteryCategoryData',$lotteryCategoryData);
        $this -> display();
    }
    /* 添加分类 */
    public function addCate(){
        $LotteryCategory = M('LotteryCategory');
        if(IS_POST){
            /* 接值 */
            $id = trim(I('post.id',''));
            $data['category_name'] = trim(I('post.category_name','')); //分类名称

            /* 验证 */
            $validateMsg = $this -> categoryValidate($data);
            if($validateMsg){
                $this -> error($validateMsg);
                exit;
            }
            /* 添加 */
            if($id){
                $data['id'] = $id;
                $data['update_time'] = time(); //修改时间
                $insert_id = $LotteryCategory -> save($data);
            }else{
                $data['create_time'] = time(); //创建时间
                $insert_id = $LotteryCategory -> add($data);
            }

            if($insert_id){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
            exit;
        }
        if(IS_GET){
            $id = trim(I('get.id',''));
            if($id){
                $LotteryCategoryData = $LotteryCategory->where('id = '.$id)->find();
            }
        }
        $this -> assign('LotteryCategoryData',$LotteryCategoryData);
        $this -> display();
    }
    /* 数据验证 */
    public function categoryValidate($data){
        $info[] = $data;
        $str = '';
        foreach ($info as $k => $v){
            if(empty($v['category_name'])){
                $str = '分类名称不能为空';
            }
        }
        return $str;
    }
    /* 删除分类 */
    public function delCate(){
        if(IS_POST){
            $id = trim(I('post.id',''));
            if(!$id){
                exit(json_encode(['result' => 401,'message' => '无法获取分类id','data' => []]));
            }
            $LotteryCategory = M('LotteryCategory');
            $result = $LotteryCategory->where('id='.$id)->delete(); //
            if(!$result){
                exit(json_encode(['result' => 402,'message' => '操作失败','data' => []]));
            }else{
                exit(json_encode(['result' => 200,'message' => '操作成功','data' => []]));
            }
        }
    }

    /*
     * 奖品配置相关
     * */

    /* 配置列表 */
    public function configList(){
        $lotteryConfig = M('lotteryConfig');
        $configData = $lotteryConfig ->field('id,name,key,value') -> select();
        foreach ($configData as $k => &$v){
            if($v['key'] == 'lotteryStartTime' || $v['key'] == 'lotteryEndTime'){
                $v['value'] = date('Y-m-d H:i:s',$v['value']);
            }
        }
        $this -> assign('configData',$configData);
        $this -> display();
    }

    /* 配置添加 */
    public function addConfig(){
        $LotteryConfig = M('LotteryConfig');
        if(IS_POST){
            /* 接值 */
            $id = trim(I('post.prize_id',''));
            $data['name'] = trim(I('post.name','')); //配置名称
            $data['value'] = trim(I('post.value','')); //配置值
            if(!is_numeric($data['value'])&&empty($data['value'])){
                $this->error('配置值不能为空');
            }
            /* 添加 */
            if($id){
                $data['id'] = $id;
                $data['update_time'] = time(); //创建时间
                $insert_id = $LotteryConfig -> save($data);
            }else{
                $data['create_time'] = time(); //创建时间
                $insert_id = $LotteryConfig -> add($data);
            }
            if($insert_id){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
            exit;
        }
        if(IS_GET){
            $id = trim(I('get.id',''));
            if($id){
                $configData = $LotteryConfig->where('id = '.$id)->find();
            }
        }
        $this -> assign('configData',$configData);
        $this -> display();
    }

    /* 删除配置 */
    public function delconfig(){
        if(IS_POST){
            $id = trim(I('post.id',''));
            if(!$id){
                exit(json_encode(['result' => 401,'message' => '无法获取奖品id','data' => []]));
            }
            $LotteryConfig = M('LotteryConfig');
            $result = $LotteryConfig->where('id='.$id)->delete(); //
            if(!$result){
                exit(json_encode(['result' => 402,'message' => '操作失败','data' => []]));
            }else{
                exit(json_encode(['result' => 200,'message' => '操作成功','data' => []]));
            }
        }
    }

    /*
     * 抽奖记录
     * */
    /* 记录列表 */
    public function recordList(){
        $where['category_id'] = ['NEQ',0];
        $keyWord = trim(I('get.key_word',''));
        $grant = trim(I('get.grant',''));
        if($keyWord){
            $where['prize_name|nickname']  = ['like',"%$keyWord%"];
            $whereLike['key_word'] = $keyWord;
        }
        if($grant){
            $where['grant']  = $grant;
            $whereLike['grant'] = $grant;
        }
        /* 近期获奖用户 */
        $lotteryRecord = M('LotteryRecord');
        $count = $lotteryRecord
                -> join('ln_users ON ln_users.user_id = ln_lottery_record.user_id')
                -> join('ln_lottery_prize On ln_lottery_prize.prize_id = ln_lottery_record.prize_id')
                -> join('ln_lottery_category On ln_lottery_prize.category_id = ln_lottery_category.id')
                -> where($where)
                -> count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数
        foreach($whereLike as $key=>$val) {
            $Page->parameter[$key] = $val;
        }
        $show = $Page->show();// 分页显示输出
        $lotteryRecordData = $lotteryRecord
                        -> join('ln_users ON ln_users.user_id = ln_lottery_record.user_id')
                        -> join('ln_lottery_prize On ln_lottery_prize.prize_id = ln_lottery_record.prize_id')
                        -> join('ln_lottery_category On ln_lottery_prize.category_id = ln_lottery_category.id')
                        -> field('ln_lottery_record.id,nickname,grant,category_name,prize_name,ln_lottery_record.create_time')
                        -> where($where)
                        -> limit($Page->firstRow.','.$Page->listRows)
                        -> select();
        foreach ($lotteryRecordData as &$val){
            $val['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
        }
        $this -> assign('lotteryRecordData',$lotteryRecordData);
        $this -> assign('page',$show);
        $this -> display();
    }
    /* 修改发放记录 */
    public function changeGrant(){
        if(IS_POST){
            $id = trim(I('post.id',''));
            $status = trim(I('post.status',''));
            if(!$id || $status == ''){
                exit(json_encode(['result' => 401,'message' => '参数有误','data' => []]));
            }
            $LotteryRecord = M('LotteryRecord');
            $result = $LotteryRecord->where('id='.$id)->save(['grant' => $status]); //
            if(!$result){
                exit(json_encode(['result' => 402,'message' => '操作失败','data' => []]));
            }else{
                exit(json_encode(['result' => 200,'message' => '操作成功','data' => []]));
            }
        }
    }
}